﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Threading;
using log4net;

namespace NormalGsearch
{
    class GoogleSearchProxy
    {
        private NormalGSearchViewModel viewModel;
        private GoogleAuthenticationProxy authenticationProxy;
        private ILog logger;
        
        private Timer searchTimer;
        private static int TimerDueTime = 1000;
        private static int TimerNoInterval = Timeout.Infinite;
        private List<string> searchTerms;
        private List<string>.Enumerator enumerator;
        
        public GoogleSearchProxy(NormalGSearchViewModel viewModel, GoogleAuthenticationProxy authenticationProxy)
        {
            this.authenticationProxy = authenticationProxy;
            this.viewModel = viewModel;
            logger = LogManager.GetLogger(typeof(GoogleSearchProxy)); 
        }

        public void TriggerSearches(List<string> searchTerms)
        {
            this.searchTerms = searchTerms;
            enumerator = this.searchTerms.GetEnumerator();

            logger.Info("Starting Google searches ...");

            // create endless timer with callback EndlessTimerCallback
            TimerCallback timerDelegate = new TimerCallback(SearchTimerCallback);
            // we are passing DateTime.Now in order to see when this timer was started
            searchTimer = new Timer(timerDelegate, null, TimerDueTime, TimerNoInterval);
        }

        // Hint: search request format
        // http://www.google.com/support/enterprise/static/gsa/docs/admin/72/gsa_doc_set/xml_reference/request_format.html#1076668

        

        private void SearchTimerCallback(Object stateInfo)
        {
            if (enumerator.MoveNext())
            {
                string searchTerm = enumerator.Current;

                string uriString = "http://www.google.com/search";

                try
                {
                    WebClient webClient = new WebClient();

                    viewModel.StatusMessage = "Suche nach >" + searchTerm + "<";
                    logger.Info("Searching for >" + searchTerm + "<");

                    webClient.Headers.Add("Authorization", "GoogleLogin " + authenticationProxy.SecureId);
                    webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                    webClient.Headers.Add("accept-encoding", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    webClient.Headers.Add("accept-language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
                    // webClient.Headers.Add("accept-encoding", "gzip,deflate");
                    webClient.Headers.Add("accept-charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                    webClient.Headers.Add("keep-alive", "115");

                    webClient.Credentials = new NetworkCredential(viewModel.Username, viewModel.Password);

                    NameValueCollection nameValueCollection = new NameValueCollection();
                    nameValueCollection.Add("q", searchTerm);
                    webClient.QueryString.Add(nameValueCollection);
                    string result = webClient.DownloadString(uriString);
                }
                catch (Exception ex)
                {
                    viewModel.StatusMessage = "Suche nach >" + searchTerm + "< fehlgeschlagen!";
                    logger.Info("Search for >" + searchTerm + "< failed: " + ex);                    
                }

                searchTimer.Change(TimerDueTime, TimerNoInterval);

                // retrieve contents of <div class="sd" id="resultStats">...                
            }
            else
            {
                viewModel.StatusMessage = "Normale Suche abgeschlossen!";
                logger.Info("... ended search.");
            }

        }
    }
}
